#include <gencod.h>

#include <stdio.h>

char* codGetLine(int line){
	return codData+(line*PCOD_LINECHAR);
}

void codInit(){
	codContent = 0;
	codReserv = PCOD_STEP;
	
	codProcNb = 0;
	
	codData = malloc(PCOD_STEP*PCOD_LINECHAR*sizeof(char));
	
	int i;
	for(i=0;i<codReserv;++i){
		strcpy(codGetLine(i), "");
	}
}

int codAddLine(char* str){
	if(codContent==codReserv){
		//réalocation
		char* tmp;
		tmp = malloc((codReserv+PCOD_STEP)*PCOD_LINECHAR*sizeof(char));
		memcpy(tmp, codData, sizeof(char)*PCOD_LINECHAR*codReserv);
		free(codData);
		codData=tmp;
		codReserv += PCOD_STEP;
		int i;
		for(i=codReserv-PCOD_STEP;i<codReserv;++i){
			strcpy(codGetLine(i), "");
		}
	}
	strcpy(codGetLine(codContent), str);
	return codContent++;
}

int codAppend(char* str, int line){
	strcat(codGetLine(line), str);
	return line;
}

void codPrint(){
	int i;
	for(i=0;i<codContent;++i){
		printf("%05d %s\n",i, codGetLine(i));
		fprintf(pcod, "%05d %s\n",i, codGetLine(i));
	}
}

void codProcPush(char* name, int line){
	strcpy(codProcName[codProcNb], name);
	codProcLine[codProcNb] = line;
	++codProcNb;
}

int codProcGet(char* name){
	int i = 0;
	
	while(i<codProcNb){
		if(strcmp(codProcName[i], name)==0) return codProcLine[i];
		++i;
	}
	
	return -1;
}

/*
 * Instructions 
 */
 
int codINC(int type, int i){
	char str[80]; sprintf(str, "INC %d,%d", type, i);
	return codAddLine(str);
}

int codLOD(int type, int i){
	char str[80]; sprintf(str, "LOD %d,%d", type, i);
	return codAddLine(str);
}

int codSTO(int type, int i){
	char str[80]; sprintf(str, "STO %d,%d", type, i);
	return codAddLine(str);
}

int codOPR(int code){
	char str[80]; sprintf(str, "OPR 0,%d", code);
	return codAddLine(str);
}

int codSTP(){
	char str[80]; sprintf(str, "STP 0,0");
	return codAddLine(str);
}

int codSFL(){
	char str[80]; sprintf(str, "SFL 0,0");
	return codAddLine(str);
}

int codLIT(int type, char* val){
	char str[80]; sprintf(str, "LIT %d,%s", type, val);
	return codAddLine(str);
}

int codJPC(){
	char str[80]; sprintf(str, "JPC 0,");
	return codAddLine(str);
}

int codJMP(){
	char str[80]; sprintf(str, "JMP 0,");
	return codAddLine(str);
}

int codCAL(int line){
	char str[80]; sprintf(str, "CAL 0,%d", line);
	return codAddLine(str);
}

int codRET(){
	char str[80]; sprintf(str, "RET 0,0");
	return codAddLine(str);
}

int codNOP(){
	char str[80]; sprintf(str, "NOP 0,0");
	return codAddLine(str);
}

int codWRT(){
	return codAddLine("WRT 0,0");
}

int codWRL(){
	return codAddLine("WRL 0,0");
}

int codREA(int type){
	char str[80]; sprintf(str, "REA %d,0", type);
	return codAddLine(str);
}
